package com.hc.sp06.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import sp01.util.JsonResult;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author He
 * @date 2021/9/1 10:32
 */
@Component  //spring自动扫描，自动创建实例
public class ItemOrderFB implements FallbackProvider {
    /**
     * 设置当前降级类，是针对哪个服务的降级类
     * -item-service 只针对商品服务做降级
     * */
    @Override
    public String getRoute() {
        return "order-service";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            //返回状态码  比如500
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.GATEWAY_TIMEOUT;
            }

            //返回的是500的code值
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.GATEWAY_TIMEOUT.value();
            }

            //返回的是500的文本
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.GATEWAY_TIMEOUT.getReasonPhrase();
            }

            //关闭流的，一般用不上
            @Override
            public void close() {
            }

            // 获取协议体
            // 协议梯(响应体)
            @Override
            public InputStream getBody() throws IOException {
                String json = JsonResult.err().code(HttpStatus.GATEWAY_TIMEOUT.value()).msg("调用订单服务失败").toString();
                return new ByteArrayInputStream(json.getBytes("UTF-8"));
            }

            /**
             * 响应头
             * */
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders h = new HttpHeaders();
                h.add("Content-Type", "application/json;charset=UTF-8");
                return h;
            }
        };
    }
}
